package com.yk.rabbitmq.routing;

import com.rabbitmq.client.*;

import java.io.IOException;


public class Consumer implements Runnable {

    public void run() {
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("localhost");
        connectionFactory.setPort(5672);
        connectionFactory.setUsername("admin");
        connectionFactory.setPassword("12345");
        connectionFactory.setVirtualHost("/faith");

        Connection connection = null;
        Channel channel = null;
        try {
            connection = connectionFactory.newConnection("生产者");
            channel = connection.createChannel();
            final String queueName = Thread.currentThread().getName();
            channel.basicConsume(queueName, true, new DeliverCallback() {
                public void handle(String s, Delivery delivery) throws IOException {
                    System.out.println(queueName + "收到的消息是：" + new String(delivery.getBody(), "UTF-8"));
                }
            }, new CancelCallback() {
                public void handle(String s) throws IOException {
                    System.out.println(queueName + "接收消息失败");
                }
            });
            System.out.println(queueName + "开始接收消息");
            System.in.read();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //关闭连接
            if (channel != null && channel.isOpen()) {
                try {
                    connection.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) {
        new Thread(new Consumer(), "队列1").start();
        new Thread(new Consumer(), "队列2").start();
        new Thread(new Consumer(), "队列3").start();
    }
}
